package wwl.lsf.hellospringboot.test.nio.netty聊天;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.ArrayList;
import java.util.List;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

  private static List<Channel> channels = new ArrayList<>();

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {

    Channel incoming = ctx.channel();
    channels.add(incoming);
    System.out.println("Server :" + incoming.remoteAddress().toString() + "上线了");

  }

  @Override
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {

    Channel outChannel = ctx.channel();

    System.out.println("Server" + outChannel.remoteAddress().toString() + "下线了");
    channels.remove(outChannel);
  }

  @Override
  protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s)
      throws Exception {

    Channel channel = channelHandlerContext.channel();

    channels.forEach(channel1 -> {

      if (channel1 != channel) {
        channel1.writeAndFlush(channel.remoteAddress() + "说" + s);
      }
    });

  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    System.out.println(ctx.channel().remoteAddress() + "发生异常");

    ctx.close();
  }
}
